package card;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

import javax.swing.ImageIcon;

import DAO.CardPileDao;
import game.GameJFrame;
import realCard.CardSha;
import realCard.CardShan;
import realCard.CardTao;
import realCard.CardTaoYuanJieYi;
import realCard.CardWanJianQiFa;
import realCard.CardWuZhongShengYou;

public class CardPileDaoImpl implements CardPileDao {
	static ArrayList<Card> cardPile = new ArrayList<>();
	GameJFrame gameJFrame;
	
	public CardPileDaoImpl(GameJFrame gameJFrame) {//牌堆用构造方法
		this.gameJFrame = gameJFrame;
		initializePile();
		Collections.shuffle(cardPile);
	}
	
	public CardPileDaoImpl() {};//弃牌堆所用构造方法
	
	public Card drawCard() {
		Card card = cardPile.get(0);
		cardPile.remove(0);
		return card;
	}
	
	public void addCard(Card card) {
		cardPile.add(card);
	}
	
	public boolean isEmpty() {
		if (cardPile.size() == 0)
			return true;
		return false;
	}
	
	public void refreshPile(Object discardPile) {
		if(discardPile.getClass().equals(cardPile.getClass()))
		{
			ArrayList<Card> pile = (ArrayList<Card>)discardPile;
			cardPile.addAll(pile);
		}
	}
	
	public ArrayList<Card> getList() {
		return cardPile;
	}
	
	public void initializePile() {
		File file = new File("src/InitializedCards.txt");
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			while ((tempString = reader.readLine()) != null) {
				String temp[] = tempString.split(" ");
				switch (temp[0]) {
				case "杀":
					cardPile.add(
							new CardSha(CardColor.valueOf(temp[1]), CardRank.valueOf(temp[2]), gameJFrame, false));
					break;
				case "闪":
					cardPile.add(
							new CardShan(CardColor.valueOf(temp[1]), CardRank.valueOf(temp[2]), gameJFrame, false));
					break;
				case "桃":
					cardPile.add(
							new CardTao(CardColor.valueOf(temp[1]), CardRank.valueOf(temp[2]), gameJFrame, false));
					break;
				case"万箭齐发":
				cardPile.add(
						new CardWanJianQiFa(CardColor.valueOf(temp[1]), CardRank.valueOf(temp[2]), gameJFrame, false));
				case"桃园结义":
					cardPile.add(
							new CardTaoYuanJieYi(CardColor.valueOf(temp[1]), CardRank.valueOf(temp[2]), gameJFrame, false));
					break;
				case"无中生有":
					cardPile.add(
							new CardWuZhongShengYou(CardColor.valueOf(temp[1]), CardRank.valueOf(temp[2]), gameJFrame, false));
					break;
				}
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
	}

	public void addAll(Object cardList) {
		if(cardList.getClass().equals(cardPile.getClass()))
		{
			ArrayList<Card> pile = (ArrayList<Card>)cardList;
			cardPile.addAll(pile);
		}
		
	}
}
